Maybe, even probably. It might also reformat your hard disk drive or attempt to launch a nuke targeted at your location. Undefined behaviour, friend.Originally Posted by Tanuj_Tanmay
Maybe, even probably. It might also reformat your hard disk drive or attempt to launch a nuke targeted at your location. Undefined behaviour, friend.Originally Posted by Tanuj_Tanmay
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Use the FAQ Luke!
Quzah.
Hope is the first step on the road to disappointment.
It yields undefined behaviour, definitely, because the C standard says so.
Section J.2 of the 1999 C standard summarises many variants of undefined behaviour, one of which is;
An array subscript is out of range, even if an object is apparently accessible with the given subscript (as in the lvalue expression a[1][7] given the declaration int a[4][5]) (6.5.6).
the reason why "someone" included the terminology of "bad programming practices" is because they are bad programming practices, hence, should be avoided. I see no reason to hold on to a very buggy c[-1] let alone to defend its use.
I agree, it should be used with extreme care. But how do you propose we'd solve the problem of malloc that stores a block of data stored BEFORE the actual pay-load data returned, and when we come to free, we need to find that block of data? Of course, we could have some sort of list of allocations and search that list for the passed in pointer. But some people certainly use some form like this:
Which is about the same as the c[-1] described above.Code:void free(void *p) { ... AdminBlock *pAdmin = ((AdminBlock *)p)-1; ...
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
Well, it's not actually.
Firstly, it is up the the implementation as to how it implements malloc() and free(). The purpose of implementation defined behaviour is to allow freedom for the implementation (the compiler, standard library, etc) .... the implementation can attach any meaning to undefined behaviour that makes sense to it.
Second, if free() behaves like you describe then malloc() and friends presumably do something like;
That addition of the offset (+1) in malloc() would ensure the negative offset (-1) within free() yields a valid address within the dynamically allocated memory/array. So no need to rely on undefined behaviour.Code:void *malloc(size_t n) { AdminBlock *buffer = (AdminBlock *)get_memory_from_system(n); return (void *)(buffer + 1); }
Grumpy, yes of course, we need a matching pair where malloc allocates a bit of extra memory, and then gives the address of something WIHTIN that block of memory, with enough space for the admin block BEFORE.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.